package com.example.hello.service.impl;

import com.example.hello.mapper.CommunityCommentMapper;
import com.example.hello.pojo.CommentRequest;
import com.example.hello.pojo.CommentResponse;
import com.example.hello.pojo.CommunityComment;
import com.example.hello.service.CommunityCommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommunityCommentServiceImpl implements CommunityCommentService {

    @Autowired
    private CommunityCommentMapper mapper;

    @Override
    public List<CommentResponse> listComments(int page, int size) {
        int offset = page * size;
        // 1. 查根评论（已带 userAvatar/userNickname）
        List<CommentResponse> roots = mapper.selectRootComments(offset, size);

        // 2. 查每条根评论的回复，并直接赋值到 DTO.replies
        for (CommentResponse root : roots) {
            List<CommentResponse> replies = mapper.selectReplies(root.getId());
            root.setReplies(replies);
        }
        return roots;
    }

    @Override
    public CommentResponse addComment(CommentRequest req) {
        // 用同一个 DTO 类来传参，也能映射 userId,parentId,toUserId,content
        CommentResponse toInsert = new CommentResponse();
        BeanUtils.copyProperties(req, toInsert);
        mapper.insert(toInsert);
        // 刚插入以后 toInsert.id 就有了，但 avatar/nickname/toUserNickname 还得重新查
        // 简化：直接调用 listComments(0,1) 拿最新的一条根或回复
        if (req.getParentId() == null) {
            CommentResponse fresh = mapper.selectRootComments(0, 1).get(0);
            fresh.setReplies(Collections.emptyList());
            return fresh;
        } else {
            // 如果是回复，去查 replies
            List<CommentResponse> replies = mapper.selectReplies(req.getParentId());
            // 找到刚插入的
            return replies.stream()
                    .filter(r -> r.getId().equals(toInsert.getId()))
                    .findFirst()
                    .orElseThrow();
        }
    }

    @Override
    public void deleteComment(Long id) {
        mapper.deleteById(id);
    }
}